﻿namespace Jerky.Helper;

/// <summary>
/// XML帮助类
/// </summary>
/// <remarks>用于读写XML文件</remarks>
static class XMLHelper
{
    /// <summary>
    /// 加载XML文档
    /// </summary>
    /// <param name="filePath">XML文件路径</param>
    /// <returns>加载的XDocument</returns>
    public static XDocument LoadXml(string filePath)
    {
        return XDocument.Load(filePath);
    }

    /// <summary>
    /// 保存XML文档
    /// </summary>
    /// <param name="document">要保存的XDocument</param>
    /// <param name="filePath">目标文件路径</param>
    public static void SaveXml(XDocument document, string filePath)
    {
        document.Save(filePath);
    }

    /// <summary>
    /// 查找第一个匹配的元素
    /// </summary>
    /// <param name="document">XDocument文档</param>
    /// <param name="elementName">元素名称</param>
    /// <returns>匹配的XElement</returns>
    public static XElement? FindElement(XDocument document, string elementName)
    {
        return document.Descendants(elementName).FirstOrDefault();
    }

    /// <summary>
    /// 查找具有指定名称的所有元素。
    /// </summary>
    /// <param name="document">XML 文档。</param>
    /// <param name="elementName">元素名称（XName）。</param>
    /// <returns>匹配的元素集合。</returns>
    public static IEnumerable<XElement> FindElements(XDocument document, XName elementName)
    {
        return document.Descendants(elementName);
    }

    /// <summary>
    /// 替换元素内容
    /// </summary>
    /// <param name="element">要替换内容的XElement</param>
    /// <param name="newContent">新的内容</param>
    public static void ReplaceElementContent(XElement element, string newContent)
    {
        if (element != null)
        {
            element.Value = newContent;
        }
    }
}
